<template>
    <n-layout>
        <n-layout-header>
            <div class="stock_query--info">
                <n-select style="width:180px" v-model:value="queryList.status" :options="accomStatusDict"
                    :placeholder="$t('placeholder.orderStatus')" clearable>
                </n-select>
            </div>
            <div class="stock_query--info">
                <n-button @click="refreshList" type="info" :loading="loading">{{ $t("button.query") }}</n-button>
                <n-button @click="handleOperation('add');" type="primary" :disabled="loading">{{ $t("button.newOrder")
                    }}</n-button>
            </div>
        </n-layout-header>
        <n-layout-content content-style="height:calc(100vh - 135px);padding:0 20px;">
            <n-table :single-line="false">
                <thead class="stock_table--header">
                    <tr>
                        <th align="center" width="10%">{{ $t("tableColumnLabel.bossName") }}</th>
                        <th align="center" width="10%">{{ $t("tableColumnLabel.proxyUserName") }}</th>
                        <th align="center" width="10%">{{ $t("tableColumnLabel.accompanyName") }}</th>
                        <th align="center" width="10%">{{ $t("tableColumnLabel.bossPay") }}</th>
                        <th align="center" width="20%">{{ $t("tableColumnLabel.accompanyTime") }}</th>
                        <th align="center" width="15%">{{ $t("tableColumnLabel.bossTel") }}</th>
                        <th align="center" width="10%">{{ $t("tableColumnLabel.orderStatus") }}</th>
                        <th align="center" width="15%">{{ $t("tableColumnLabel.operation") }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td colspan="8" align="center">
                            <n-spin size="small" style="margin: 10px 0;"></n-spin>
                        </td>
                    </tr>
                    <template v-else>
                        <tr v-if="userList.length === 0">
                            <td colspan="8" align="center">{{ $t("text.noDate") }}</td>
                        </tr>
                        <tr v-else v-for="(item, index) in userList" :key="index">
                            <td align="center">
                                {{ item.bossName }}
                            </td>
                            <td align="center">
                                {{ item.proxyUserName }}
                            </td>
                            <td align="center">
                                <span v-if="item.accomUser.name">{{ item.accomUser.name }}</span>
                                <n-tag v-else :bordered="false" type="error">
                                    {{ $t("text.deleteAccomWarning") }}
                                </n-tag>
                            </td>
                            <td align="center">
                                ￥{{ item.bossPay }}
                            </td>
                            <td align="center">
                                {{ item.startTime }} {{ $t("text.to") }} {{ item.endTime }}
                            </td>
                            <td align="center">
                                {{ item.bossTel }}
                            </td>
                            <td align="center">
                                <n-tag size="small" :type="item.status === '0' ? 'success' : 'error'">
                                    {{accomStatusDict.find(dict => dict.value === item.status)?.label || '无'}}
                                </n-tag>
                            </td>
                            <td align="center">
                                <div class="btn__list--grid">
                                    <n-button size="small" type="primary" @click="handleOperation('view', item)">{{
                                        $t("button.trace") }} </n-button>
                                    <template v-if="item.status !== '3'">
                                        <n-button size="small" type="error" @click="handleOperation('delete', item)"> {{
                                            $t("button.delete") }}</n-button>
                                        <!-- 0 下单 1付账 2陪玩 3结单 -->
                                        <n-button size="small" type="info" @click="handleOperation('charge', item)">{{
                                            ['0', '1'].includes(item.status)
                                                ? $t("button.openOrder") : $t("button.renewal") }}</n-button>
                                    </template>
                                    <n-button v-if="item.status === '2'" size="small" type="info"
                                        @click="finishOrder(item)">
                                        {{ $t("button.overOrder") }}
                                    </n-button>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </n-table>
        </n-layout-content>
        <n-layout-footer>
            <n-pagination v-model:page="queryList.page" v-model:page-size="queryList.limit"
                :item-count="queryList.total" show-size-picker :page-sizes="[10, 20, 30, 40]"
                @update:page="handlePageChange($event, 'page')" @update:page-size="handlePageChange($event, 'limit')" />
        </n-layout-footer>
    </n-layout>
</template>

<script setup lang='ts' name="OrderListComp">
import { getOrders, deleteOrder, changeOrderStatus } from '@/api/backend/order';
import { updateStockStatus } from '@/api/backend/stock';
import { useDialog, useMessage } from 'naive-ui';
import { getByTag } from '@/api/backend/admin';
import i18n from '@/locales';
import EventEmiiter from '@/utils/EventEmiiter';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const { userInfo } = userStore;
const { t } = i18n.global;
const router = useRouter();
const queryList = reactive({
    status: '',
    page: 1,
    limit: 10,
    total: 0
});
const userList = reactive<OrderVO[]>([]);
const accomStatusDict = reactive<{
    label: string;
    value: string;
}[]>([]);
const loading = ref(false);
const message = useMessage();
const dialog = useDialog();
const emit = defineEmits<{
    (event: 'toDetail', type: 'view' | 'charge', row: Partial<OrderVO>): void
}>();
// 初始化字典
const initDict = async () => {
    try {
        const [res1] = await Promise.all([getByTag('accomStatus')]);
        accomStatusDict.length = 0; // 清空数组
        accomStatusDict.push({
            label: '全部',
            value: ''
        });
        res1.data.forEach((item: Dict) => {
            accomStatusDict.push({
                label: item.label,
                value: item.value
            });
        });
    } catch (error) {
        message.error(`获取字典失败-${error}`);
    }
};
initDict()
const refreshList = async () => {
    try {
        loading.value = true;
        const { data, total } = await getOrders(queryList);
        userList.length = 0;
        queryList.total = total as number;
        (data ?? []).forEach(item => {
            userList.push(item);
        });
    } catch (error) {
        message.error(`获取库存列表失败: ${error}`);
    } finally {
        loading.value = false;
        EventEmiiter.emit('VIEW:CHANGE_LOADING', false);
    }
}
const handleOperation = (type: 'add' | 'view' | 'delete' | 'charge', row?: OrderVO) => {
    if (type === 'add') {
        router.push('/home/accomUser');
        EventEmiiter.emit('VIEW:CHANGE_MENU', '/home/accomUser');
    } else if (type === 'view') {
        emit('toDetail', type, row!);
    } else if (type === 'delete') {
        if(userInfo.id !== row?.proxyUserId) return message.error('不能删除其他代理的订单！');
        handleDelete(row!.id, row!.accomId);
    } else if (type === 'charge') {
        emit('toDetail', 'charge', row!);
    }
}
refreshList();
const handleDelete = async (orderId: string, accomId: string) => {
    dialog.warning({
        title: t('text.warning'),
        content: t('text.delteOrder'),
        positiveText: t('text.confirm'),
        negativeText: t('text.cancel'),
        draggable: true,
        onPositiveClick: async () => {
            try {
                EventEmiiter.emit('VIEW:CHANGE_LOADING', true);
                loading.value = true;
                const response = await deleteOrder(orderId, accomId);
                if (response.code !== 200) throw new Error(response.message);
                await updateStockStatus(accomId, '0');
                message.success('Delete Successfully!');
            } catch (error) {
                message.error(`Delte Errorly: ${error}`);
            } finally {
                refreshList();
            }
        },
        onNegativeClick: () => {
            message.error('Cancel!')
        }
    })
};

const handlePageChange = (value: number, prop: 'page' | 'limit') => {
    Object.assign(queryList, {
        [prop]: value
    })
    refreshList();
}

// 结单
const finishOrder = async (row: OrderVO) => {
    if (new Date() <= new Date(row.endTime)) return message.error('尚未到陪玩结束时间，无法结单！');
    try {
        loading.value = true;
        await changeOrderStatus('3', row.id);
        //修改陪玩状态
        await updateStockStatus(row.accomUser.id, '0')
        message.success('结单成功！');
        refreshList();
    } catch (error) {
        message.error(error instanceof Error ? error.message : '错误！');
    } finally {
        loading.value = false;
    }
}
</script>
<style scoped lang='scss'>
.n-layout-header {
    height: 60px;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .stock_query--info {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
    }
}

.n-layout-footer {
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 20px;
    background: rgba(255, 255, 255, 0.2);
    /* 半透明背景 */
    backdrop-filter: blur(10px);
    /* 背景模糊 */
    -webkit-backdrop-filter: blur(10px);
    /* 兼容性前缀 */
    border-top: 1px solid #E7E7E7;
    /* 可选边框 */
}

.stock_table--header th {
    background: rgb(233, 240, 247);
}

table tr td {
    background: none;
}

table tr:hover {
    background: rgb(250, 252, 255) !important;
    cursor: pointer;
}

.btn__list--grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 4px;
}
</style>